<template>
  <div class="flex enterpriseKnowledge">
    <div class="aside">
      <el-row :gutter="20" justify="space-between">
        <el-col :span="22">企业知识库</el-col>
        <el-col :span="2">
          <el-button type="primary" text @click="addClass">添加分类</el-button>
        </el-col>
      </el-row>

      <div v-for="(item, index) in classHostList" :key="index" @click="clickClass(item)">
        <div class="item">{{ item.name }}</div>
        <el-popover placement="right" :width="400" trigger="click">
          <template #reference>
            <svg-icon iconClass="icon_more" />
          </template>
          <el-button type="primary" text @click="handleHotClassEdit(item)">编辑</el-button>
          <el-button type="primary" text @click="handleHotClassDelete(item)">删除</el-button>
        </el-popover>
      </div>
    </div>
    <div class="main">
      <div>
        <el-row :gutter="20" class="toolbar">
          <el-col :span="4">
            <el-button type="primary" @click="addQuestion">添加问题</el-button>
          </el-col>
          <el-col :span="8">
            <el-input v-model="searchKeyword" placeholder="输入搜索关键词" clearable>
              <template #append>
                <el-button icon="el-icon-search" @click="search"></el-button>
              </template>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-select v-model="enabled" placeholder="状态" clearable>
              <el-option label="正常" :value="1"></el-option>
              <el-option label="停用" :value="0"></el-option>
            </el-select>
          </el-col>
          <el-col :span="4">
            <!-- <el-button @click="importData">导入数据</el-button> -->
            <!-- <el-button @click="exportData">导出数据</el-button> -->
          </el-col>
        </el-row>

        <el-table :data="filteredQuestions" style="width: 100%">
          <el-table-column prop="question" label="标准问题" width="180"></el-table-column>
          <el-table-column prop="enabled" label="当前状态" width="100">
            <template #default="scope">
              <el-button type="text">{{ scope.row.enabled ? "正常" : "停用" }}</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="updated" label="操作时间" width="180">
            <template #default="scope">
              <el-button type="text">{{ fotmatDay(scope.row.updated) }}</el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button type="text" @click="editQuestion(scope.row)">编辑</el-button>
              <el-button type="text" @click="toggleStatus(scope.row)">
                {{ scope.row.enabled ? "停用" : "启用" }}
              </el-button>
              <el-button type="text" @click="deleteQuestion(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          background
          layout="prev, pager, next"
          :total="totalQuestions"
          :page-size="limit"
          v-model:current-page="page"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </div>

    <!-- 新增 | 编辑分类 -->
    <el-dialog :title="classDialogTitle" v-model="classDialogVisible" width="30%">
      <el-form
        :model="classDetailItem"
        ref="formRef"
        label-width="120px"
        label-position="top"
        :rules="rules"
      >
        <el-form-item label="分类名字" prop="name">
          <el-input
            v-model="classDetailItem.name"
            type="text"
            @keyup.enter="handleSubmitClassName"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span>
          <el-button @click="classDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitClassName">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog :title="questionTitle" v-model="questionVisbile" width="70%">
      <el-form
        :model="questionForm"
        ref="questionRef"
        label-width="120px"
        label-position="top"
        :rules="questionFormRules"
      >
        <el-form-item label="标准问题" prop="question">
          <el-input v-model="questionForm.question" placeholder="输入内容" />
        </el-form-item>
        <el-form-item label="相似问法" prop="similarQuestions">
          <el-input v-model="questionForm.similarQuestions" placeholder="输入相似问法" />
        </el-form-item>
        <el-form-item label="默认回答" prop="answer">
          <el-input type="textarea" v-model="questionForm.answer" placeholder="输入内容" />
        </el-form-item>
        <el-form-item label="选择分类" prop="cid">
          <el-select v-model="questionForm.cid" placeholder="选择选项">
            <el-option
              v-for="item in allClassList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span>
          <el-button @click="questionVisbile = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitQuestion">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from "vue";
import { USER_MODEL } from "@/constants/index";
import storage from "@/utils/localforage/index";

import { ElMessage } from "element-plus";
import {
  knowledgeBaseSetStatus,
  knowledgeBaseDelete,
  knowledgeBaseAddorupdate,
  knowledgeBaseAnsewer,
  knowledgeBaseDdetail,
  knowledgeBaseHotTableData,
  knowledgeBaseTableData,
  knowledgeBaseSearch,
  knowledgeBaseUnidentified,
  addknowledgeBaseClassification,
  knowledgeBaseClassificationHotList,
  knowledgeBaseClassificationList,
  updateKnowledgeBaseClassification,
} from "@/api/node-admin-api/class.js";
import { successMessage, warnMessage, errorMessage } from "@/utils/message";
import dayjs from "dayjs";

const classHostList = ref([]);
const filteredQuestions = ref([]);
const loading = ref(false);
const searchKeyword = ref("");
const enabled = ref("");
const page = ref(1);
const limit = ref(10);
const totalQuestions = ref(0);

onMounted(() => {
  getHotClassList();
});

// 获取热门分类列表
const getHotClassList = () => {
  loading.value = true;
  knowledgeBaseClassificationHotList({ params: 999 })
    .then((res) => {
      if (res.code == 20000) {
        classHostList.value = [{ name: "全部分类" }, ...res.data.records];
      }
    })
    .catch((e) => {
      errorMessage(e.message);
    })
    .finally((res) => {
      loading.value = false;
    });
};

const fotmatDay = (val) => {
  return dayjs(new Date(val)).format("YYYY-MM-DD HH:mm:ss");
};

// 获取全部分类
const allClassList = ref([]);
loading.value = true;
const getAllClassList = () => {
  knowledgeBaseTableData()
    .then((res) => {
      if (res.code == 20000) {
        allClassList.value = res.data.records;
      }
    })
    .catch((e) => {
      errorMessage(e.message);
    })
    .finally((res) => {
      loading.value = false;
    });
};

const classDetailItem = ref({ name: "" });
const classDialogTitle = ref("");
const classDialogVisible = ref(false);
// 添加热门分类
const addClass = (item) => {
  classDialogTitle.value = true;
  classDialogTitle.value = "添加分类";
  classDetailItem.value = { name: "" };
};

// 根据分类检索问题
const clickClass = (item) => {
  searchKeyword.value = "";
  enabled.value = "";
  if (item.name == "全部分类") {
    getQuestionByUserId();
  } else {
    getQuestionByClassId(item);
  }
};
// 获取这个用户全部分类的问题
const getQuestionByUserId = () => {
  loading.value = true;
  const userInfo = storage.get(USER_MODEL);
  const params = {
    userId: userInfo.userId,
    keyword: searchKeyword,
  };
  knowledgeBaseTableData(params)
    .then((res) => {
      if (res.code == 20000) {
        filteredQuestions.value = res.data.records;
      }
    })
    .catch((e) => {
      errorMessage(e.message);
    })
    .finally((res) => {
      loading.value = false;
    });
};

// 根据热门分类检索问题
const getQuestionByClassId = (item) => {};

// 编辑热门分类
const handleHotClassEdit = (item) => {
  classDialogTitle.value = true;
  classDialogTitle.value = "编辑分类";
  classDetailItem.value = { ...item };
};

const handleSubmitClassName = () => {
  if (!classDetailItem.value.name) {
    errorMessage("请输入分类名字！");
    return;
  }
  loading.value = true;

  if (classDialogTitle.value == "编辑分类") {
    const prams = {
      ...classDetailItem.value,
      name: classDetailItem.value,
      isDelete: false,
    };
    updateKnowledgeBaseClassification(prams)
      .then((res) => {
        if (res.code == 20000) {
          successMessage("新增分类成功！");
          classDialogVisible.value = false;
          getHotClassList();
        }
      })
      .catch((e) => {
        errorMessage(e.message);
      })
      .finally((res) => {
        loading.value = false;
      });
  } else {
    addknowledgeBaseClassification({ name: classDetailItem.value.name })
      .then((res) => {
        if (res.code == 20000) {
          successMessage("新增分类成功！");
          classDialogVisible.value = false;
          getHotClassList();
        }
      })
      .catch((e) => {
        errorMessage(e.message);
      })
      .finally((res) => {
        loading.value = false;
      });
  }
};
// 删除热门分类
const handleHotClassDeleet = (item) => {
  loading.value = true;
  const prams = {
    ...classDetailItem.value,
    isDelete: true,
  };
  updateKnowledgeBaseClassification(prams)
    .then((res) => {
      if (res.code == 20000) {
        successMessage("删除分类成功！");
        classDialogVisible.value = false;
        getHotClassList();
      }
    })
    .catch((e) => {
      errorMessage(e.message);
    })
    .finally((res) => {
      loading.value = false;
    });
};

const questionTitle = ref("");
const questionVisbile = ref(false);
const questionForm = ref({
  question: "",
  similarQuestions: "",
  answer: "",
  cid: "",
});

const questionFormRules = ref({
  question: [{ required: true, message: "请输入标准问题", trigger: "blur" }],
  answer: [{ required: true, message: "请输入默认回答", trigger: "blur" }],
  cid: [{ required: true, message: "请选择分类", trigger: "change" }],
});

const categoryOptions = [
  { value: "category1", label: "分类1" },
  { value: "category2", label: "分类2" },
  { value: "category3", label: "分类3" },
];

const handleSubmitQuestion = () => {
  questionRef.value.validate((valid) => {
    if (valid) {
      // 提交表单逻辑
      console.log("提交表单", form.value);
    } else {
      console.log("表单验证失败");
      return false;
    }
  });
};

const addQuestion = () => {
  getAllClassList();
  questionTitle.value = "添加问题";
  questionForm.value = {
    question: "",
    similarQuestions: "",
    answer: "",
    cid: "",
    id: 0,
  };
  questionVisbile.value = true;
};

const editQuestion = (row) => {
  getAllClassList();
  questionTitle.value = `编辑问题: ${row.question}`;
  questionForm.value = { ...row };
  questionVisbile.value = true;
};

// 检索问题
const search = () => {
  successMessage("搜索功能");
  const params = {
    question: searchKeyword.value,
    limit: limit.value,
    page: page.value,
    enabled: Boolean(enabled.value),
  };
  loading.value = true;
  knowledgeBaseSearch(params)
    .then((res) => {
      if (res.code == 20000) {
        filteredQuestions.value = res.data.records || [];
      }
    })
    .catch((e) => {
      errorMessage(e.message);
    })
    .finally((res) => {
      loading.value = false;
    });
};

const importData = () => {
  successMessage("导入数据功能");
};

const exportData = () => {
  successMessage("导出数据功能");
};

// 更新状态
const toggleStatus = (row) => {
  const params = {
    id: row.id,
    enabled: row.enabled ? false : true,
  };
  loading.value = true;
  knowledgeBaseSetStatus(params)
    .then((res) => {
      if (res.code == 20000) {
        successMessage(`状态已更新!`);
        search();
      }
    })
    .catch((e) => {
      errorMessage(e.message);
    })
    .finally((res) => {
      loading.value = false;
    });
};

// 删除知识库
const deleteQuestion = (row) => {
  const params = {
    id: row.id,
  };
  loading.value = true;
  knowledgeBaseDelete(params)
    .then((res) => {
      if (res.code == 20000) {
        successMessage(`问题已删除!`);
        search();
      }
    })
    .catch((e) => {
      errorMessage(e.message);
    })
    .finally((res) => {
      loading.value = false;
    });
};

const handlePageChange = (page) => {
  page.value = page;
};
</script>

<style lang="scss" scoped>
.enterpriseKnowledge {
}
.aside {
  width: 180px;
  min-width: 180px;
  height: 100%;
  padding: 3px 8px 8px;
  border-right: 1px solid #00000017;
}
</style>
